package controllers.mobile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.Validate;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aton.config.BizConstants;
import com.aton.config.Config;
import com.aton.config.ReturnCode;
import com.aton.db.SessionFactory;
import com.aton.util.CollectionUtils;
import com.aton.util.JsonUtil;
import com.aton.util.NumberUtils;
import com.aton.util.StringUtils;
import com.google.common.base.Strings;
import com.google.gson.JsonParser;
import com.sun.jmx.snmp.tasks.TaskServer;

import controllers.TaskCenter;
import controllers.TaskExecutor;
import domain.BuyerTaskProcessor;
import domain.TaskStats;
import enums.BuyerTaskStepType;
import enums.Device;
import enums.Platform;
import enums.TaskStatus;
import enums.TaskType;
import enums.pay.PayPlatform;
import mobile.secure.MobileApiSecure;
import mobile.service.TaskService;
import mobile.vo.Result;
import models.BuyerAccount;
import models.BuyerTask;
import models.BuyerTaskStep;
import models.FundAccount;
import models.SysConfig;
import models.Task;
import models.TaskItemSearchPlan;
import models.TaskOrderMessage;
import models.User;
import models.SysConfig.SysConfigKey;
import models.User.VipStatus;
import models.mappers.BuyerTaskMapper;
import models.mappers.BuyerTaskStepMapper;
import play.data.validation.Min;
import play.data.validation.Required;
import play.mvc.With;
import vos.BuyerAccountSearchVo;
import vos.BuyerAccountSearchVo.ExamineStatus;
import vos.BuyerTaskStepVo;
import vos.BuyerTaskVo;
import vos.Page;
import vos.TaskSearchVo;

@With(MobileApiSecure.class)
public class TaskController extends BaseController {

	public static final Logger logger = LoggerFactory.getLogger(TaskController.class);
	public static final Logger buyerTaskStepLog = LoggerFactory.getLogger("taskstep");

	/**
	 * 查询用户列表
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月8日
	 * @param vo
	 * @param type
	 */
	public static void listTask(@Required TaskSearchVo vo) {

		handleWrongInput(false);

		validation.min(vo.pageNo, 1);
		validation.max(vo.pageSize, 50);
		validation.isTrue(vo.appPlatform != null);
		handleWrongInput(false);

		User cuser = getCurrentUser();
		vo.buyerId = cuser.id;
		Page<Task> page = Task.listUserBuyerCanAccpetTask(vo);
		for (Task t : page.items) {
			t.resolveId();
			markTaskStatus(t);
		}
		renderJSON(Result.optSuccessWithData(page));
	}

	/**
	 * 标记当前任务的可领取状态
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月19日
	 */
	private static void markTaskStatus(Task task) {
		BuyerAccountSearchVo vo = new BuyerAccountSearchVo();
		if (task.platform == Platform.TAOBAO || task.platform == Platform.TMALL) {
			vo.platform = Platform.TAOBAO;
		} else {
			vo.platform = task.platform;
		}
		vo.status = ExamineStatus.EXAMINED;
		vo.userId = getCurrentUser().id;
		List<BuyerAccount> accountList = BuyerAccount.findForTakingTask(vo);

		if (accountList.size() == 0) {
			task.tags = false;
			return;
		}
		boolean canFetch = false;
		for (BuyerAccount obj : accountList) {
			BuyerTask bt = new BuyerTask();
			bt.buyerAccountId = obj.id;
			bt.device = Device.MOBILE;
			boolean r = isTakeTasks(bt, task);
			canFetch = canFetch | r;
		}
		task.tags = canFetch;
	}

	private static boolean isCollection(List<BuyerTaskVo> lists, long buyerid) {
		// TODO Auto-generated method stub
		boolean iscollection = true;
		if (lists == null || lists.size() == 0) {
			return true;
		}
		for (BuyerTaskVo v : lists) {
			if (v.collectionType == null) {
				iscollection = false;
				break;
			}
			BuyerTaskStep laststep = BuyerTaskStep.findBuyerLastStep(v.id, buyerid);
			if (laststep == null) {
				iscollection = false;
				break;
			}
			if (laststep.type.getOrder() < BuyerTaskStepType.VIEW_AND_INQUIRY.getOrder()) {
				iscollection = false;
				break;
			}
		}
		return iscollection;
	}

	/**
	 * 判断是否可以接手
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月19日
	 * @param bt
	 * @param tasks
	 * @return
	 */
	private static boolean isTakeTasks(BuyerTask bt, Task task) {

		// 存在未完成的任务【提示：买号异常】
		User buyer = getCurrentUser();
		if (bt.buyerAccountId <= 0) {
			task.tags = false;
			task.reason = "买号没有绑定";
			return false;
		}

		BuyerAccount buyerAccount = BuyerAccount.findById(bt.buyerAccountId);
		if (!BuyerAccount.validate(buyerAccount, buyer)) {
			task.tags = false;
			task.reason = "买号异常";
			return false;
		}

		// 该任务已被用户接手过，不能重复领取【提示：已经领取过】
		if (BuyerTask.isDuplicateTaking(bt.buyerAccountId, task.id)) {
			task.tags = false;
			task.reason = "已经领取过";
			return false;
		}
		// 判断是否有没有做完的任务。
		List<BuyerTaskVo> bto = BuyerTask.findTodoTasks(buyer.id);
		boolean isConllection = isCollection(bto, buyer.id);
		if (!isConllection) {
			task.tags = false;
			task.reason = "有未完成的任务";
			return false;
		}

		// 父任务数据异常【提示：任务状态有误】
		if (task == null || task.status != TaskStatus.PUBLISHED) {
			task.tags = false;
			task.reason = "任务状态有误";
			return false;
		}

		// 领取非“平台返款”的任务需要绑定【财付通】作为退款账号【提示：未绑定财付通】
		if (BooleanUtils.isFalse(task.sysRefund)) {
			FundAccount bank = FundAccount.findBankAccount(buyer.id);
			if (bank==null) {
				task.tags = false;
				task.reason = "未绑定银行卡信息";
				return false;
			}
		}

		// 金币不足需要充值购买才能接手任务【提示：金币不足】
		if (buyer.ingot < BizConstants.TASK_TAKING_INGOT) {
			task.tags = false;
			task.reason = "金币不足";
			return false;
		}

		// 平台限制每个【买号】5单/天，30单/周，90单/月
		TaskStats taskStats = TaskStats.findForBuyerUntilNow(bt.buyerAccountId);

		String day = SysConfig.getConfigValue(SysConfigKey.BUYER_TASK_DAY_COUNT);
		if (StringUtils.isEmpty(day)) {
			day = Config.BUYER_TASK_DAY_COUNT;
		}

		String week = SysConfig.getConfigValue(SysConfigKey.BUYER_TASK_WEEK_COUNT);
		if (StringUtils.isEmpty(week)) {
			week = Config.BUYER_TASK_WEEK_COUNT;
		}

		String mouth = SysConfig.getConfigValue(SysConfigKey.BUYER_TASK_MONTH_COUNT);
		if (StringUtils.isEmpty(mouth)) {
			mouth = Config.BUYER_TASK_MONTH_COUNT;
		}
		// 【提示：当日已做完】
		if (taskStats.dayCount >= Integer.parseInt(day)) {
			logger.warn("BuyerAccount={} has taken {} tasks Today", bt.buyerAccountId, taskStats.dayCount);
			task.tags = false;
			task.reason = "当日任务已做完";
			return false;
		}
		// 【提示：本周已做完】
		if (taskStats.weekCount >= Integer.parseInt(week)) {
			logger.warn("BuyerAccount={} has taken {} tasks this Week", bt.buyerAccountId, taskStats.weekCount);
			task.tags = false;
			task.reason = "本周任务已做完";
			return false;
		}
		// 【提示：本月已做完】
		if (taskStats.monthCount >= Integer.parseInt(mouth)) {
			logger.warn("BuyerAccount={} has taken {} tasks this Month", bt.buyerAccountId, taskStats.monthCount);
			task.tags = false;
			task.reason = "本月任务已做完";
			return false;
		}

		bt.buyerId = buyer.id;
		// 账号和商家之间的限制【提示：账号和商家之间的限制】
		if (task.platform == Platform.TAOBAO || task.platform == Platform.TMALL) {
			// 目前只限制淘宝平台,其他平台不做限制。
			if (!isAvailableBuyerIdAndSellerId(buyer.id, task.sellerId)) {
				task.tags = false;
				task.reason = "该商家的任务已经领取过";
				return false;
			}
		}

		// 账号和店铺之间的限制【提示：账号和店铺之间的限制】
		if (!isAvailableBuyerIdAndShopId(buyer.id, task.shopId)) {
			return false;
		}
		// 买号和店铺之间的限制【提示：买号和店铺之间的限制】
		if (!isValidateBuyerAccountAndShopId(bt.buyerAccountId, task.shopId)) {
			task.tags = false;
			task.reason = "该店铺的任务已经领取过";
			return false;
		}
		// System.out.println(task.type.toString());
		// 买号和商品之间的限制【提示：买号和商品之间的限制】
		if (!isAvailableBuyerAccountAndItem(bt.buyerAccountId, task.itemId, task.type.toString())) {
			task.tags = false;
			task.reason = "该商品的任务已经领取过";
			return false;
		}
		task.tags = true;
		return true;
	}

	public static boolean isAvailableBuyerIdAndShopId(long buyerId, long shopId) {
		List<BuyerTaskVo> shopBuyerTasks = TaskStats.findBuyerIdAndShopId(buyerId, shopId);
		if (CollectionUtils.isNotEmpty(shopBuyerTasks)) {
			return false;
		}
		return true;
	}

	/**
	 * 查询任务列表
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月24日
	 * @param vo
	 * @param type
	 */
	public static void listBuyerTasks(@Required TaskSearchVo vo, String type) {
		if (vo == null) {
			vo = new TaskSearchVo();
			vo.pageNo = 1;
			vo.pageSize = 20;
		}
		User buyer = getCurrentUser();
		Page<BuyerTaskVo> p = null;
		if ("WAIT_PAY".equals(StringUtils.trim(type))) {
			p = BuyerTask.findBuyerTaskListForApp(
					vo.buyerId(buyer.id).statusIn(TaskStatus.RECIEVED, TaskStatus.WAIT_PAY));
		} else if ("WAIT_CONFIRM".equals(StringUtils.trim(type))) {
			p = BuyerTask.findBuyerTaskListForApp(vo.buyerId(buyer.id).statusIn(TaskStatus.WAIT_SEND_GOODS, 
					TaskStatus.WAIT_EXPRESS_PRINT, TaskStatus.EXPRESS_PRINT, TaskStatus.WAIT_CONFIRM));
		} else if ("WAIT_SYS_REFUND".equals(StringUtils.trim(type))) {
			p = BuyerTask.findBuyerTaskListForApp(vo.buyerId(buyer.id).statusIn(TaskStatus.WAIT_BUYER_CONFIRM_EDITED_SYS_REFUND, TaskStatus.WAIT_SELLER_CONFIRM_SYS_REFUND,
					TaskStatus.WAIT_BUYER_CONFIRM_SYS_REFUND, TaskStatus.WAIT_REFUND));
		} else if ("ALL".equals(StringUtils.trim(type))) {
			p = BuyerTask.findBuyerTaskListForApp(vo.buyerId(buyer.id));
		}
		for (BuyerTaskVo taskVo : p.items) {
			taskVo.subShopNamePrefix();
		}

		renderJSON(Result.optSuccessWithData(p));
	}

	/**
	 * 抓取任务详情
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月26日
	 * @param taskId
	 */
	public static void getBuyerTaskDetail(@Required Long taskId) {

		handleWrongInput(false);

		renderJSON(Result.optSuccessWithData(findBuyerTaskDetail(taskId)));
	}

	private static Map<String, Object> findBuyerTaskDetail(Long taskId) {

		Map<String, Object> data = new HashMap<String, Object>();

		User user = getCurrentUser();
		long currentTaskId = taskId;
		BuyerTask buyerTask = BuyerTask.findById(currentTaskId);
		BuyerTaskStep laststep = BuyerTaskStep.findBuyerLastStep(currentTaskId, user.id);

		BuyerTaskStepType nextStep = null;

		if (laststep == null) {
			if (buyerTask != null && Task.isTaoBaoAndTmall(buyerTask.taskId)) {
				nextStep = BuyerTaskStepType.ORDER_AND_PAY;
			} else {
				nextStep = BuyerTaskStepType.CHOOSE_ITEM;
			}
		} else {
			nextStep = laststep.type.getNext();
		}

		data.put("currentStep", nextStep);

		BuyerTaskVo task = BuyerTask.findForPerforming(currentTaskId, user.id);

		notFoundIfNull(task);

		task.id = currentTaskId;

		// 设置任务当前要做的步骤：前端页面上显示的小步骤
		int initTaskStepNo = 1;
		if (nextStep == BuyerTaskStepType.VIEW_AND_INQUIRY) {
			initTaskStepNo = 2;
		}
		if (nextStep == BuyerTaskStepType.ORDER_AND_PAY) {
			initTaskStepNo = 4;
		}

		data.put("currentStepNo", initTaskStepNo);

		// 随机取出一条订单留言
		data.put("orderMessage", TaskOrderMessage.getOneMessage(task.taskId));

		// 取出一套搜索方案
		if (task.searchPlanId > 0) {
			data.put("searchPlan", TaskItemSearchPlan.findById(task.searchPlanId));
		} else {
			data.put("searchPlan", TaskItemSearchPlan.getOnePlanOld(task.taskId));
		}
		Task t = Task.findById(task.taskId);

		task.collectionType = t.collectionType;

		if ((t.platform == Platform.TAOBAO || t.platform == Platform.TMALL || t.platform == Platform.JD
				|| t.platform == Platform.MOGUJIE || t.platform == Platform.MEILISHUO) && t.type != TaskType.JHS) {
			data.put("isTaoBaoAndTmall", true);
		} else {
			data.put("isTaoBaoAndTmall", false);
		}

		data.put("collectionRequest", t.collectionRequest);
		data.put("taskInfo", task);
		data.put("taskPlatform", task.platform);

		return data;
	}

	/**
	 * 保存任务
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月27日
	 * @param id
	 * @param type
	 * @param vo
	 * @param messageId
	 * @param currentStep
	 */
	public synchronized static void saveTaskStep(@Required @Min(1) long id, @Required BuyerTaskStepType type,
			@Required BuyerTaskStepVo vo, long messageId) {

		handleWrongInput(false);

		BuyerTask buyerTask = BuyerTask.findById(id);
		boolean result = Task.isTaoBaoAndTmall(buyerTask.taskId);
		User buyer = getCurrentUser();
		Object[] args = new Object[] { buyer.id, buyer.nick, id, type.toString() };
		logger.info("Buyer={}-{} perform buyerTask={} save step={}", args);

		Long taskId = buyerTask.id;

		if (vo.picUrls != null && vo.picUrls.size() == 1) {
			String picUrl = vo.picUrls.get(0);
			vo.picUrls.clear();
			String[] picUrls = picUrl.split(",");
			vo.picUrls.addAll(Arrays.asList(picUrls));
		}

		if (vo.itemUrls != null && vo.itemUrls.size() > 0) {
			String itemUrl = vo.itemUrls.get(0);
			vo.itemUrls.clear();
			String[] itemUrls = itemUrl.split(",");
			vo.itemUrls.addAll(Arrays.asList(itemUrls));
		}

		if (!result) {
			/*
			 * 检查任务步骤应包含的数据
			 */
			// 第一步“挑选商品”：四个其他商品链接
			if (type == BuyerTaskStepType.CHOOSE_ITEM && !vo.validateUrls(vo.picUrls, 2)) {
				renderJSON(Result.invalidParamWithMsg("数据不全，请检查"));
			}
			// 第三步“浏览店铺及询盘”：四个其他商品链接，一个聊天截图的图片url
			if (type == BuyerTaskStepType.VIEW_AND_INQUIRY
					&& (!vo.validateUrls(vo.itemUrls, 1) || !vo.validateUrls(vo.picUrls, 3))) {
				renderJSON(Result.invalidParamWithMsg("数据不全，请检查"));
			}

			/*
			 * 检查上个做完的步骤
			 */
			logger.info("Fetch and Check Buyer={} last perform step of buyerTask={}", buyer.id, id);

			BuyerTaskStep lastTaskStep = BuyerTaskStep.findBuyerLastStep(taskId, buyer.id);
			// 上个步骤记录不存在时，当前步骤必须是第一步“货比三家”
			if (lastTaskStep == null && type != BuyerTaskStepType.CHOOSE_ITEM) {
				logger.error("[Buyer={}-{} perform buyerTask={} save step={}] Input step must be first:[CHOOSE_ITEM]",
						args);
				renderJSON(Result.errorWithMsg("系统检测到数据异常，该操作被拒绝，请退出重新登录，若问题依旧请与管理员联系解决~~"));
			}
			// 上个步骤记录存在时，当前步骤必须为“上个步骤记录的下一个步骤”
			if (lastTaskStep != null && type != lastTaskStep.type.getNext()) {
				Object[] args3 = new Object[] { buyer.id, buyer.nick, id, type.toString(), taskId, type.title };
				logger.error("[Buyer={}-{} perform buyerTask={} save step={}] taskId={} step={}", args3);
				renderJSON(Result.errorWithMsg("系统检测到数据异常，该操作被拒绝，请退出重新登录，若问题依旧请与管理员联系解决~~"));
			}

			args = new Object[] { type.toString(), buyer.id, id, };
			logger.info("Sessoin current taskStep={} ,buyer={},buyerTask={}", args);

			if (lastTaskStep != null) {
				args = new Object[] { buyer.id, lastTaskStep.id, lastTaskStep.type.toString(), id };
				logger.info("Buyer={} last perform step={}[{}] of buyerTask={}", args);
			}
		}
		/*
		 * 检查正在做的任务(状态)
		 */
		if (buyerTask == null || buyerTask.isNotBelongTo(buyer)
				|| (buyerTask.status != TaskStatus.WAIT_PAY && buyerTask.status != TaskStatus.RECIEVED)) {
			renderJSON(Result.invalidParamWithMsg("数据不全，请检查"));
		}

		// 第五步下单支付：检查用户填写的“订单号”及“付款金额”
		if (type == BuyerTaskStepType.ORDER_AND_PAY) {
			validation.isTrue(vo.validateUrls(vo.picUrls, 1));
			validation.isTrue(StringUtils.isNumeric(vo.orderNo));
			validation.isTrue(NumberUtils.isNumber(vo.realPaidFee));
			validation.required(messageId);
			validation.min(messageId, 1);
			handleWrongInput(false);

			// 设置随机分配的订单留言记录
			buyerTask.messageId = messageId;
		}

		args = new Object[] { buyer.id, buyer.nick, type.toString(), buyerTask.taskId, buyerTask.id, buyerTask.status };
		logger.info("Buyer={}-{} perform save step={} of buyerTask={}-{} with status={}", args);

		BuyerTaskStep.newInstance(buyerTask.id, buyer.id).type(type).content(vo).create(buyerTask);

		/*
		 * 更新当前要做的任务步骤标记
		 */
		if (BuyerTaskStepType.ORDER_AND_PAY == type) {
			renderJSON(Result.optSuccess());
		} else {
			// 更新当前任务进行的步骤为下一个步骤
			renderJSON(Result.optSuccessWithData(type.getNext()));
		}
	}

	/**
	 * 撤消任务
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月27日
	 * @param id
	 */
	public static void cancelBuyerTask(@Required @Min(1) long id) {
		handleWrongInput(false);

		User buyer = getCurrentUser();
		BuyerTask bt = BuyerTask.findById(id);
		if (bt == null || bt.isNotBelongTo(buyer)) {
			renderJSON(Result.invalidParamWithMsg("参数错误"));
		}

		// 状态限制
		if (bt.status != TaskStatus.RECIEVED && bt.status != TaskStatus.WAIT_PAY) {
			renderJSON(Result.errorWithMsg("该任务当前状态下不能撤销任务"));
		}

		Object[] args = new Object[] { buyer.id, buyer.nick, bt.taskId, bt.id };
		logger.info("Buyer={}-{} cancle buyerTask={}-{}", args);

		// 撤销任务
		bt.cancel();

		renderJSON(Result.optSuccess());
	}

	/**
	 * 检查端口连接
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月27日
	 * @param itemUrl
	 */
	public static void checkItem(@Required String itemUrl, @Required @Min(0) Long buyerTaskId) {
		validation.isTrue(StringUtils.isNotBlank(itemUrl));
		// 限制最大长度300个字符串
		validation.maxSize(itemUrl, 300);
		handleWrongInput(false);

		// 获取买手当前正在做的任务
		long buyerId = getCurrentUser().id;
		BuyerTaskVo taskVo = BuyerTask.findVoById(buyerTaskId, buyerId);
		if (taskVo == null || taskVo.status != TaskStatus.WAIT_PAY) {
			Object[] args = new Object[] { buyerId, itemUrl, buyerTaskId };
			logger.warn("User={} check item_url={} for buyerTask={} FAIL:[data error]", args);
			renderJSON(Result.invalidParamWithMsg("你输入的商品链接不正确"));
		}

		// 先比较商品url是否完全一致
		if (taskVo.itemUrl.equals(itemUrl)) {
			renderJSON(Result.optSuccess());
		}

		// 若url不完全一致，则从商品链接中提取商品ID与任务目标商品进行比较
		String inputItemId = Task.getItemIdByPlatform(taskVo.platform, itemUrl);

		if (Strings.isNullOrEmpty(inputItemId) || !inputItemId.equals(taskVo.itemId.toString())) {
			renderJSON(Result.invalidParamWithMsg("你输入的商品链接不正确"));
		}
		renderJSON(Result.optSuccess());
	}

	/**
	 * 查询能领取此任务的账号
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月29日
	 * @param taskId
	 */
	public static void getBuyerAccount(@Required Long taskId) {

		handleWrongInput(false);

		User user = getCurrentUser();

		renderJSON(Result.optSuccessWithData(BuyerAccount.selectAvailableAccountByTaskId(taskId, user.id)));
	}

	/**
	 * 领取任务
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月30日
	 * @param bt
	 */
	public synchronized static void take(@Required BuyerTask bt) {
		if (bt != null) {
			validation.required(bt.taskId);
			validation.required(bt.buyerAccountId);
			validation.required(bt.buyerAccountNick);
		}
		bt.device = Device.MOBILE;
		handleWrongInput(false);

		User buyer = getCurrentUser();
		BuyerAccount buyerAccount = BuyerAccount.findById(bt.buyerAccountId);
		if (!BuyerAccount.validate(buyerAccount, buyer)) {
			logger.error("买手={}违规注册多个账号，本次使用买号={}不属于当前登录用户！", buyer.nick, bt.buyerAccountNick);
			renderJSON(Result.errorWithMsg("当前登录用户状态异常，请退出后再登录~~"));
		}

		// 该任务已被用户接手过，不能重复领取
		if (BuyerTask.isDuplicateTaking(bt.buyerAccountId, bt.taskId)) {
			renderJSON(Result.errorWithMsg("你已经领取过该任务了，换一个吧~~"));
		}
		// 存在尚未完成的任务，不能领取新任务
		BuyerTask todoTask = BuyerTask.findTodoTask(buyer.id);
		List<BuyerTaskVo> bto=BuyerTask.findTodoTasks(buyer.id);
        boolean isConllection=isCollection(bto,buyer.id);
        if(!isConllection){
        	renderJSON(Result.errorWithMsg("你已领取其它任务，请完成后再试！"));
        }

		// 父任务数据异常
		Task task = getTask(bt.taskId);
		if (task == null || task.status != TaskStatus.PUBLISHED) {
			renderJSON(Result.errorWithMsg("当前任务异常不能领取！"));
		}

		if (BooleanUtils.isFalse(task.sysRefund)) {
			FundAccount bank = FundAccount.findBankAccount(getCurrentUser().id);
			if (bank==null) {
				renderJSON(Result.errorWithMsg("未绑定银行卡信息"));
			}
		}

		// 任务已全被领取完
		if (task.isTakenOver(bt.device)) {
			renderJSON(Result.errorWithMsg("当前任务已无领取名额"));
		}

		// 金币不足需要充值购买才能接手任务
		if (buyer.ingot < BizConstants.TASK_TAKING_INGOT) {
			renderJSON(Result.errorWithMsg("您的金币不足，无法领取任务~~"));
		}

		// 平台限制每个【买号】5单/天，30单/周，90单/月
		TaskStats taskStats = TaskStats.findForBuyerUntilNow(bt.buyerAccountId);

		String day = SysConfig.getConfigValue(SysConfigKey.BUYER_TASK_DAY_COUNT);
		if (StringUtils.isEmpty(day)) {
			day = Config.BUYER_TASK_DAY_COUNT;
		}

		String week = SysConfig.getConfigValue(SysConfigKey.BUYER_TASK_WEEK_COUNT);
		if (StringUtils.isEmpty(week)) {
			week = Config.BUYER_TASK_WEEK_COUNT;
		}

		String mouth = SysConfig.getConfigValue(SysConfigKey.BUYER_TASK_MONTH_COUNT);
		if (StringUtils.isEmpty(mouth)) {
			mouth = Config.BUYER_TASK_MONTH_COUNT;
		}

		if (taskStats.dayCount >= Integer.parseInt(day)) {
			logger.warn("BuyerAccount={} has taken {} tasks Today", bt.buyerAccountId, taskStats.dayCount);
			renderJSON(Result.errorWithMsg("该买号今日可领取任务已达上限"));
		}
		if (taskStats.weekCount >= Integer.parseInt(week)) {
			logger.warn("BuyerAccount={} has taken {} tasks this Week", bt.buyerAccountId, taskStats.weekCount);
			renderJSON(Result.errorWithMsg("该买号本周可领取任务已达上限"));
		}
		if (taskStats.monthCount >= Integer.parseInt(mouth)) {
			logger.warn("BuyerAccount={} has taken {} tasks this Month", bt.buyerAccountId, taskStats.monthCount);
			renderJSON(Result.errorWithMsg("该买号本月可领取任务已达上限"));
		}

		bt.buyerId = buyer.id;

		// 账号和商家之间的限制
		if (task.platform == Platform.TAOBAO || task.platform == Platform.TMALL)// 目前只限制淘宝平台的
			if (!isAvailableBuyerIdAndSellerId(buyer.id, task.sellerId)) {
				renderJSON(Result.errorWithMsg("你在该商家已经领取过任务"));
			}

		// 买号和店铺之间的限制
		if (!isValidateBuyerAccountAndShopId(bt.buyerAccountId, task.shopId)) {
			renderJSON(Result.errorWithMsg("该买号已在该店铺已经领取过任务"));

		}
		// 买号和商品之间的限制
		if (!isAvailableBuyerAccountAndItem(bt.buyerAccountId, task.itemId, task.type.toString())) {
			renderJSON(Result.errorWithMsg("该买号号已经领取过该任务"));
		}
		// TODO 新手必须完成新手任务后才能接手其他任务
		// BuyerAccount.findForTakingTask(vo)
		// task.searchPlans
		boolean result = Task.isTaoBaoAndTmall(bt.taskId);// 除淘宝、天猫外的其他平台
		Object[] args = new Object[] { buyer.id, buyer.nick, bt.taskId };
		buyerTaskStepLog.info("Buyer={}-{} take Task={}", args);

		/*
		 * 创建买手任务记录
		 */
		bt.sellerId = task.sellerId;
		bt.pledgeIngot = BizConstants.TASK_TAKING_INGOT * 100L;
		bt.rewardIngot = task.calculateRewardIngot(bt.device);
		// 评论上传图片，给买手0.5个金币
		if (StringUtils.isNotEmpty(task.goodCommentImg)) {
			bt.rewardIngot += 50;
		}
		// 写入任务的经验值
		User seller = User.findByIdWichCache(task.sellerId);
		bt.experience = task.getListType(seller.registTime).experience;
		if (result) {
			bt.status = TaskStatus.WAIT_PAY;
		} else {
			bt.status = TaskStatus.RECIEVED;
		}
		// 关键词对应已接单数加1
		TaskItemSearchPlan p = TaskItemSearchPlan.getOnePlan(bt.taskId);
		if (p != null && p.takenNum < p.totalNum) {
			p.takenNum += 1;
			TaskItemSearchPlan.update(p);
			bt.searchPlanId = p.id;
		}
		bt.create();

		renderJSON(Result.optSuccessWithData(findBuyerTaskDetail(bt.id)));
	}

	private static Task getTask(long taskId) {
		// 父任务数据异常
		return Task.findById(
				"id,platform,status,base_order_ingot,extra_reward_ingot,pc_order_num,mobile_order_num,pc_taken_count,mobile_taken_count,"
						+ "finished_count,seller_id,create_time,shop_id,item_id,sys_refund,"
						+ "publish_timer_interval,publish_timer_value,last_batch_publish_time,good_comment_img,type",
				taskId);
	}

	private static boolean isAvailableBuyerIdAndSellerId(long buyerId, long sellerId) {
		if (getCurrentUser().vipStatus == VipStatus.SPECIAL || getCurrentUser().vipStatus == VipStatus.AIZHUAN) {
			return true;
		}
		List<BuyerTaskVo> buyerSellerTasks = TaskStats.findBuyerIdAndSellerId(buyerId, sellerId);
		if (CollectionUtils.isNotEmpty(buyerSellerTasks)) {
			return false;
		}
		return true;
	}

	private static boolean isValidateBuyerAccountAndShopId(long buyerAccountId, Long shopId) {
		Validate.notNull(buyerAccountId);
		Validate.notNull(shopId);
		// 取【最近15天】【该买号】在【该商家】的（非取消）任务记录
		List<BuyerTaskVo> buyerTasks = TaskStats.findBuyerAccountIdAndShopId(buyerAccountId, shopId);

		if (CollectionUtils.isNotEmpty(buyerTasks)) {
			return false;
		}
		return true;
	}

	private static boolean isAvailableBuyerAccountAndItem(long buyerAccountId, String itemId, String type) {
		// System.out.println(itemId);
		Validate.notNull(buyerAccountId);
		if (!"JHS".equals(type)) {
			Validate.notEmpty(itemId);
			if (CollectionUtils
					.isNotEmpty(TaskStats.selectByBuyerAccountIdAndItemIdAndPeriod(buyerAccountId, itemId))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 查询需要确认收货的任务
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月1日
	 * @param platform
	 * @param id
	 */
	public static void getConfirmRecvTask(@Required long id) {
		handleWrongInput(false);
		// 获取待处理的任务
		TaskSearchVo vo = TaskSearchVo.newInstance().buyerId(getCurrentUser().id).buyerTaskId(id);
		List<BuyerTaskVo> list = BuyerTask.findListForConfirm(vo);
		for (BuyerTaskVo buyerTaskVo : list) {
			SqlSession ss = SessionFactory.getSqlSession();
			Map map = new HashMap<String, Object>();
			try {
				BuyerTaskStepMapper stepMapper = ss.getMapper(BuyerTaskStepMapper.class);
				BuyerTaskStep buyerTaskStep2 = stepMapper.selectByTaskIdAndTypeAndBuyerId(id, BuyerTaskStepType.REFUND_TASK_NOT_END, getCurrentUser().id);
				if(buyerTaskStep2!=null&&StringUtils.isEmpty(buyerTaskVo.transNo)&&StringUtils.isNotEmpty(buyerTaskStep2.content)){
					String content = buyerTaskStep2.content;
					JsonParser parser = new JsonParser();
					String no = parser.parse(content).getAsJsonObject().get("transNo").getAsString();
					buyerTaskVo.transNo = no;
				}
			}finally{
				ss.close();
			}
			buyerTaskVo.value();
		}
		renderJSON(Result.optSuccessWithData(list));
	}

	/**
	 * 确认收货
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月2日
	 * @param id
	 * @param vo
	 */
	public static void confirmRecvGoods(@Required long id, @Required BuyerTaskStepVo vo) {
		if (vo != null) {
			validation.required(vo.picUrls);
			// 该功能仅上传一张图片，校验第一个即可
			String picUrl = vo.picUrls.get(0);
			validation.required(picUrl);
			validation.url(picUrl);
		}
		handleWrongInput(false);

		// 检查任务是否存在、是否所属当前用户、是否待确认发货
		BuyerTask buyerTask = BuyerTask.findById(id);
		buyerTask.confirmGoodsAndRate(vo);
		renderJSON(Result.optSuccess());
	}

	/**
	 * 查询待确认返款的任务详情
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月3日
	 * @param vo
	 */
	public static void getConfirmRefundTask(@Required TaskSearchVo vo) {
		handleWrongInput(false);
		BuyerTaskVo task = BuyerTask.getSysRefundTask(vo);
		if (task == null) {
			renderJSON(Result.resourceNotFoundWithMsg("要操作的记录不存在"));
		}
		task.value();
		renderJSON(Result.optSuccessWithData(task));
	}

	/**
	 * 确认返款
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月3日
	 * @param id
	 * @param isReject
	 */
	public synchronized static void confirmRefund(@Required @Min(1) long id, boolean isReject) {
		handleWrongInput(false);
		BuyerTask buyerTask = BuyerTask.findById(id);
		User buyer = getCurrentUser();
		if (buyerTask == null || buyerTask.isNotBelongTo(buyer)
				|| (buyerTask.status != TaskStatus.WAIT_BUYER_CONFIRM_SYS_REFUND
						&& buyerTask.status != TaskStatus.WAIT_BUYER_CONFIRM_EDITED_SYS_REFUND)) {
			if (isReject) {
				logger.warn("Buyer={} reject sysRefund of buyerTask={} with status={}", buyer.id, id, buyerTask.status);
			} else {
				logger.warn("Buyer={} confirm sysRefund of buyerTask={} with status={}", buyer.id, id,
						buyerTask.status);
			}
			renderJSON(Result.invalidParamWithMsg("参数错误"));
		}
		BuyerTaskProcessor.confirmSysRefund(buyerTask, isReject);

		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 商家返款
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年2月12日
	 * @param bt
	 */
	public synchronized static void sellerRefundConfirm(@Required BuyerTask bt) {
		if (bt != null) {
			validation.required(bt.id);
			validation.required(bt.taskId);
			validation.required(bt.status);
		}
		handleWrongInput(false);
		
		BuyerTask buyerTask = BuyerTask.findById(bt.id);
		User buyer = getCurrentUser();
			if (buyerTask == null || buyerTask.isNotBelongTo(buyer) || buyerTask.status != TaskStatus.REFUNDING) {
				renderJSON(Result.errorWithMsg("任务信息错误"));
		}
		buyerTask.confirmSellerRefund();
		renderJSON(Result.optSuccess());
	}
	

	/**
	 * 删除任务
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月12日
	 * @param id
	 */
	public static void delBuyerTask(@Required Long id) {
		handleWrongInput(false);

		BuyerTask.del(id, getCurrentUser().id);

		renderJSON(Result.optSuccess());

	}
	
	/**
	 * 查询习手任务详情
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年2月5日
	 * @param id
	 */
	public static void getBueryTaskDetailForView(@Required Long id){
		handleWrongInput(false);
		
		BuyerTaskVo buyerTask = BuyerTask.findBuyerTaskDetailForView(id, getCurrentUser().id);
		
		notFoundIfNull(buyerTask);
		
		buyerTask.value();
		
		renderJSON(Result.optSuccessWithData(buyerTask));
		
	}

}
